﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;

namespace ThienLoc.Admin
{
    public partial class DangSanPham : System.Web.UI.Page
    {
        private static int IDSanPham;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadListSanPham();
                LoadHangSP(ddlMenu);
                MultiView1.ActiveViewIndex = 1;
            }
        }

        protected void LoadListSanPham()
        {
            string sql = "select m.ID,m.Image,m.TenMonAn,m.MoTa,m.GiaTien from tblTLMonAn m";
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
            grvData.DataSource = dt;
            grvData.DataBind();
        }

        protected void LoadListSanPham(int MenuID)
        {
            string sql = "select m.ID,m.Image,m.TenMonAn,m.MoTa,m.GiaTien from tblTLMonAn m where m.Menu_ID = @Menu_ID OR @Menu_ID = -1 ORDER BY s.UpdateDate DESC";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@Menu_ID", SqlDbType.Int, ParameterDirection.Input, MenuID));
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql, arrParams);
            grvData.DataSource = dt;
            grvData.DataBind();
        }

        protected void SuaSanPham()
        {
            string sql = "";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            SqlTransaction Mytrans = SqlHelper.BeginTransaction();
            try
            {
                string img = "";
                if (txtAnhSP.HasFile)
                {
                    img += "Image = @Image,";
                    arrParams.Add(SqlHelper.CreateParameterObject("@Image", SqlDbType.NVarChar, ParameterDirection.Input, UploadFile()));
                }
                sql = "UPDATE tblTLMonAn set TenMonAn = @TenMonAn, Menu_ID = @Menu_ID,  " + img +
                      "MoTa = @MoTa	,GiaTien = @GiaTien,UpdateDate = GETDATE() WHERE ID = @ID";

                arrParams.Add(SqlHelper.CreateParameterObject("@TenMonAn", SqlDbType.NVarChar, ParameterDirection.Input, txtTenMonAn.Text));
                arrParams.Add(SqlHelper.CreateParameterObject("@Menu_ID", SqlDbType.Int, ParameterDirection.Input, cboMenu.SelectedValue));
                arrParams.Add(SqlHelper.CreateParameterObject("@GiaTien", SqlDbType.NVarChar, ParameterDirection.Input, Convert.ToDouble(txtGiaTien.Text.Equals("") ? "0" : txtGiaTien.Text)));
                arrParams.Add(SqlHelper.CreateParameterObject("@MoTa", SqlDbType.NVarChar, ParameterDirection.Input, txtGhiChu.Value));
                arrParams.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, IDSanPham));
                SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
                Mytrans.Commit();
            }
            catch (Exception ex)
            {
                Mytrans.Rollback();
            }
        }

        protected void ThemSanPham()
        {
            string sql = "";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            SqlTransaction Mytrans = SqlHelper.BeginTransaction();
            try
            {

                sql = "INSERT INTO tblTLMonAn(Menu_ID,Image,TenMonAn,GiaTien,MoTa,CreateDate,UpdateDate) " +
                      "VALUES (@Menu_ID,@Image,@TenMonAn,@GiaTien,@MoTa,GETDATE(),GETDATE())";

                arrParams.Add(SqlHelper.CreateParameterObject("@Menu_ID", SqlDbType.Int, ParameterDirection.Input, cboMenu.SelectedValue));
                arrParams.Add(SqlHelper.CreateParameterObject("@Image", SqlDbType.NVarChar, ParameterDirection.Input, UploadFile()));
                arrParams.Add(SqlHelper.CreateParameterObject("@TenMonAn", SqlDbType.NVarChar, ParameterDirection.Input, txtTenMonAn.Text));
                arrParams.Add(SqlHelper.CreateParameterObject("@GiaTien", SqlDbType.NVarChar, ParameterDirection.Input, Convert.ToDouble(txtGiaTien.Text.Equals("") ? "0" : txtGiaTien.Text)));
                arrParams.Add(SqlHelper.CreateParameterObject("@MoTa", SqlDbType.NVarChar, ParameterDirection.Input, txtGhiChu.Value));
                SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
                Mytrans.Commit();
            }
            catch (Exception ex)
            {
                Mytrans.Rollback();
            }
        }

        protected void grvData_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string sID = e.CommandArgument.ToString().Trim();
            string sCommandName = e.CommandName;
            if (sCommandName == ThienLoc.MyConst.Action.Approve)
            {
                btnLuu.CommandName = MyConst.Action.Approve;
                MultiView1.ActiveViewIndex = 0;
                LoadChiTietSanPham(Convert.ToInt32(sID));
                IDSanPham = Convert.ToInt32(sID);
            }
            if (sCommandName == MyConst.Action.Delete)
            {
                string sql = "SELECT Image FROM dbo.tblTLMonAn WHERE ID = " + sID;
                string FileName = SqlHelper.ExecuteScalar(CommandType.Text, sql).ToString();
                sql = "DELETE FROM dbo.tblTLMonAn WHERE ID = " + sID;
                SqlHelper.ExecuteNonQuery(CommandType.Text, sql);
                try
                {
                    File.Delete(Server.MapPath("../" + FileName));
                }
                catch (Exception ex)
                {
                    Response.Write("Không có file ảnh");
                }
            }
            grvData.EditIndex = -1;
            LoadListSanPham();
        }

        private void LoadChiTietSanPham(int sID)
        {
            LoadHangSP(cboMenu);
            string sql = "SELECT * FROM dbo.tblTLMonAn WHERE ID = " + sID;
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
            cboMenu.SelectedValue = dt.Rows[0]["Menu_ID"].ToString(); ;
            txtTenMonAn.Text = dt.Rows[0]["TenMonAn"].ToString();
            if (dt.Rows[0]["Image"] == DBNull.Value)
            {
                imgAnhSP.ImageUrl = "../images/no_image.jpg";
            }
            else
            {
                imgAnhSP.ImageUrl = "../" + dt.Rows[0]["Image"].ToString();
            }
            txtGhiChu.Value = dt.Rows[0]["MoTa"].ToString();
        }

        protected void grvData_RowEditing(object sender, GridViewEditEventArgs e)
        {
            grvData.EditIndex = e.NewEditIndex;
            LoadListSanPham();
        }

        protected void grvData_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grvData.EditIndex = -1;
            LoadListSanPham();
        }

        protected void grvData_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            grvData.DeleteRow(e.RowIndex);
            grvData.DataBind();
        }

        protected void btnLuu_Click(object sender, EventArgs e)
        {
            if (btnLuu.CommandName == MyConst.Action.Addnew)
            {
                ThemSanPham();
            }
            else
            {
                SuaSanPham();
            }
            LoadListSanPham();
            MultiView1.ActiveViewIndex = 1;
        }

        protected void btnThemMoi_Click(object sender, EventArgs e)
        {
            btnLuu.CommandName = MyConst.Action.Addnew;
            MultiView1.ActiveViewIndex = 0;
            LoadHangSP(cboMenu);
            ClearField();
        }

        private void ClearField()
        {
            txtTenMonAn.Text = "";
            cboMenu.SelectedValue = "-1";
            txtGhiChu.Value = "";
        }

        protected void LoadHangSP(DropDownList ddl)
        {
            string sql = "SELECT * FROM dbo.tblTLMenu";
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
            ddl.DataSource = dt;
            ddl.DataTextField = "Ten";
            ddl.DataValueField = "ID";
            ddl.DataBind();
            ddl.Items.Insert(0, new ListItem("Chọn nhóm danh mục hiển thị", "-1"));
        }
        protected void btnHuy_Click(object sender, EventArgs e)
        {
            ClearField();
            MultiView1.ActiveViewIndex = 1;
        }

        private string UploadFile()
        {
            try
            {
                if (txtAnhSP.HasFile)
                {
                    string sFolderPath = Server.MapPath(@"../uploads/imgmonan");
                    HttpPostedFile myFile = txtAnhSP.PostedFile;
                    string sFileName = myFile.FileName;
                    string[] arrFileName = sFileName.Split('.');
                    arrFileName[0] = arrFileName[0] + "_" + DateTime.Now.ToString("ddMMyyhhssmm");
                    sFileName = arrFileName[0] + "." + arrFileName[1];
                    myFile.SaveAs(string.Format(@"{0}\{1}", sFolderPath, sFileName));
                    return "uploads/imgmonan/" + sFileName;
                }
                else
                {
                    return "";
                }
            }
            catch (Exception)
            {
                return "";
            }
        }

        protected void grvData_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvData.PageIndex = e.NewPageIndex;
            grvData.DataBind();
        }

        protected void ddlMenu_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadListSanPham(Convert.ToInt32(ddlMenu.SelectedValue));
        }
    }
}
